package com.tian.service.impl;

import com.tian.dto.coupon.UserActivityCouponPageReqDto;
import com.tian.dto.user.UserCouponAddDto;
import com.tian.dto.user.UserCouponRecordListRespDto;
import com.tian.entity.ActivityCoupon;
import com.tian.enums.ResultCode;
import com.tian.mapper.ActivityCouponMapper;
import com.tian.service.UserCouponService;
import com.tian.util.CommonResult;
import com.tian.util.RedisConstantPre;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author tianwc  公众号：java后端技术全栈、面试专栏
 * @version 1.0.0
 * @date 2023年07月27日 19:38
 * 在线刷题 1200+题和1000+篇干货文章：<a href="https://woaijava.cc/">博客地址</a>
 */
@Service("decoratorCouponService")
public class DecoratorCouponServiceImpl implements UserCouponService {
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private UserCouponService userCouponService;
    @Resource
    private ActivityCouponMapper activityCouponMapper;

    @Override
    public CommonResult<Boolean> receive(UserCouponAddDto userCouponAddDto) {
        ActivityCoupon activityCoupon = activityCouponMapper.selectByPrimaryKey(userCouponAddDto.getActivityCouponId());
        Integer totalCount = activityCoupon.getTotalCount();
        int receiveCount = totalCount - activityCoupon.getRemainCount();
        if (receiveCount <= 0) {
            return CommonResult.failed(ResultCode.TREMAIN_COUNT_LIMITER);
        }
        if (totalCount == 999999) {
            return userCouponService.receive(userCouponAddDto);
        }
        //key=前缀+活动id+优惠券id
        String key = RedisConstantPre.USER_COUPON_PRE + userCouponAddDto.getActivityId() + userCouponAddDto.getCouponId();
        try {
            redissonClient.getLock(key).lock();
            return userCouponService.receive(userCouponAddDto);
        } finally {
            redissonClient.getLock(key).unlock();
        }
    }

    @Override
    public CommonResult<UserCouponRecordListRespDto> list(UserActivityCouponPageReqDto userActivityCouponPageReqDto) {
        return userCouponService.list(userActivityCouponPageReqDto);
    }

}
